<?php

class DocumentController extends CommonController {

	public function __construct() {
		parent::__construct();
	}

	public function searchAction() {
		$type = (int) $this->requestGet('type');
		$keyword = $this->requestGet('keyword');

		$query = "SELECT * FROM `document` WHERE `type`={$type} AND `title` like '%{$keyword}%'";
		$records = $db->query();
	}

	public function recordsAction() {
		$type = (int) $this->requestGet('type', 0);
		$conditions = $type ? " AND `type`={$type} " : '';

		$page = (int) $this->requestGet('page', 1);
		$pageSize = (int) $this->requestGet('pageSize', 100);
		$offset = ($page - 1) * $pageSize;

		$orderField = (int) $this->requestGet('orderField', 0);
		$orderDirection = (int) $this->requestGet('orderDirection', 1);
		$fields = array('type', 'createdAt');
		$field = isset($fields[$orderField]) ? $fields[$orderField] : $field[0];
		$direction = $orderDirection > 0 ? 'ASC' : 'DESC';
		$order = " ORDER BY `{$field}` {$direction} ";

		$totalQuery = "SELECT COUNT(`id`) as `total` FROM `document`";
		$db = $this->loadSqlite('stranger');
		$totalRow = $db->getOne($totalQuery);
		$data = array('total' => (int) $totalRow['total']);

		$query = "SELECT `id`,`type`,`title`,`createdAt` FROM `document` WHERE 1 {$conditions} {$order} LIMIT {$offset}, {$pageSize}";
		$data['records'] = $db->getAll($query);

		$this->jsonSuccess('', $data);
	}

	public function findAction() {
		$id = (int) $this->requestGet('id');
		if (!$id)
			$this->jsonError('参数错误');
		$findQuery = "SELECT * FROM `document` WHERE `id`={$id}";
		$db = $this->loadSqlite('stranger');
		$row = $db->getOne($findQuery);
		$this->jsonSuccess('', $row);
	}

	public function setAction() {
		$id = (int) $this->requestPost('id');

		$data = array(
			'type' => (int) $this->requestPost('type'),
			'source' => (int) $this->requestPost('source', 0),
			'title' => $this->requestPost('title'),
			'content' => $this->requestPost('content'),
			'createdAt' => time()
		);

		$db = $this->loadSqlite('stranger');

		if ($db->set('document', $data, $id)) {
			$this->jsonSuccess('保存成功');
		} else {
			$this->jsonError('保存失败 ' . $db->errorMessage);
		}
	}

}